package com.attendance.chdingtask.utils.dingApi;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceGetsimplegroupsRequest;
import com.dingtalk.api.request.OapiAttendanceGroupMemberusersListRequest;
import com.dingtalk.api.response.OapiAttendanceGetsimplegroupsResponse;
import com.dingtalk.api.response.OapiAttendanceGroupMemberusersListResponse;
import com.taobao.api.ApiException;

import java.util.ArrayList;
import java.util.List;

public class AttendanceHelper {
    /**
     * 获取企业考勤组数据
     * @param accessToken
     * @return
     * @throws ApiException
     */
    public static List<OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo> getAtGroupForTopVo(String accessToken) throws ApiException {
        List<OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo> list=new ArrayList<>();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getsimplegroups");
        OapiAttendanceGetsimplegroupsRequest req = new OapiAttendanceGetsimplegroupsRequest();
        for(int i=0;i<100;i++){
            req.setOffset(Long.valueOf(i));
            req.setSize(10L);
            OapiAttendanceGetsimplegroupsResponse rsp = client.execute(req, accessToken);
            if(rsp.isSuccess()){
                if(!rsp.getResult().getHasMore()){
                    list.addAll(rsp.getResult().getGroups());
                    break;
                }
                list.addAll(rsp.getResult().getGroups());
            }else {
                throw new ApiException("考勤组数据获取异常"+rsp.getErrmsg());
            }
        }
        return list;
    }

    /**
     * 获取参与考勤人员数据
     * @param groupId
     * @param accessToken
     * @return
     * @throws ApiException
     */
    public static List<String> getAtGroupUserIds(long groupId, String accessToken) throws ApiException {
        List<String> list=new ArrayList<>();
        Long cursor=0L;
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/group/memberusers/list");
        OapiAttendanceGroupMemberusersListRequest req = new OapiAttendanceGroupMemberusersListRequest();
        for (int i =0 ;i<100;i++){
            req.setOpUserId("291302405326473611");
            req.setGroupId(groupId);
            if(0L!=cursor){
                req.setCursor(cursor);
            }
            OapiAttendanceGroupMemberusersListResponse rsp = client.execute(req, accessToken);
            if(rsp.isSuccess()){
                if(rsp.getResult().getHasMore()){
                    list.addAll(rsp.getResult().getResult());
                    cursor=rsp.getResult().getCursor();
                }else {
                    list.addAll(rsp.getResult().getResult());
                    break;
                }
            }else {
                throw new ApiException("参与考勤人员获取异常"+rsp.getErrmsg());
            }
        }
        return list;
    }
}
